package Gui.Dialogs;

import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Cards.DealCard;
import Gui.GameFrame;
import Main.Defines;

public class DealCardDialog extends JDialog {
	/**
	 * 
	 */
	private static final long serialVersionUID = 5576051974883456418L;

	JLabel Title;
	JLabel Cost;
	JLabel Value;
	JPanel jp;

	private void buildUI(final DealCard DrawnCard) {
		// Draws the info for DrawnCard
		Title = new JLabel(DrawnCard.getName());
		Cost = new JLabel("It Costs: " + DrawnCard.getCost());
		Value = new JLabel("It's Worth: " + DrawnCard.getValue());
		JButton Buy = new JButton("Buy");
		JButton Cancel = new JButton("No Thanks");
		Buy.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (Defines.CP().getCash() >= DrawnCard.getCost()) {
					Defines.CP().RemoveCash(DrawnCard.getCost());

				}
				else {
					int remainder = Defines.CP().getCash()
							% Defines.LOAN_AMOUNT;
					int moneyNeeded = DrawnCard.getCost()
							- Defines.CP().getCash();
					int addToLoanAmount = moneyNeeded
							+ (Defines.LOAN_AMOUNT - moneyNeeded
									% Defines.LOAN_AMOUNT);

					AskForLoanDialog showDialog = new AskForLoanDialog(Defines
							.CP().getID(), moneyNeeded, " for this deal card.",
							addToLoanAmount);

					if (showDialog.isClosed() && showDialog.isLoanOK()) {
						Defines.CP().setLoan(
								Defines.CP().getLoan() + addToLoanAmount);
						Defines.CP().setCash(remainder);
						Defines.CP().addDealCard(DrawnCard);
					}
				}

				dispose();
			}
		});
		Cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		jp.add(Title);
		jp.add(Cost);
		jp.add(Value);
		jp.add(Buy);
		jp.add(Cancel);

	}

	public DealCardDialog(final DealCard DrawnCard) {
		setModalityType(getModalityType().APPLICATION_MODAL);
		jp = new JPanel();
		jp.setBorder(Defines.getEmptyBorderConstraints());
		jp.setLayout(new GridLayout(0, Defines.SINGLE_ROW_COLUMN_MODIFIER, 0,
				Defines.VERTICAL_PADDING));
		
		buildUI(DrawnCard);
		add(jp);
		pack();
		if (getTitle() != null) {
			FontMetrics fm = getFontMetrics(getFont());
			int width = fm.stringWidth(getTitle()) + Defines.ICON_WIDTH;
			width = (int) Math.max(width * 1.2, getPreferredSize().getWidth());
			setSize(new Dimension(width, getHeight()));
		}
		setLocationRelativeTo(GameFrame.getInstance());
		setVisible(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
	}
}
